<template>
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <ul class="menu">
        <li>
          <router-link to="/personalcenter">个人中心</router-link>
        </li>
        <li>
          <router-link to="/viewrecording" class="active">浏览记录</router-link>
        </li>
        <li class="parent-menu" :class="{ active: isSubmenuOpen }" @click="toggleSubmenu">
          <a href="#" class="parent-link">账户设置
            <span class="toggle-icon">^</span>
          </a>
          <ul class="submenu">
            <li><router-link to="/personalinfo">个人资料</router-link></li>
            <li><router-link to="/preference-settings">偏好设置</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <div class="header">
        <div class="content-header">
          <div style="display: flex; align-items: center;">
            <img :src="avatarUrl" alt="用户头像" class="avatar" />
            <span class="username">{{ displayName }}</span>
          </div>
          <router-link to="/home" class="home-button">返回主页</router-link>
        </div>
      </div>

      <div class="search-bar">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="输入商品名称或分类"
          @keyup.enter="handleSearch"
        />
        <button @click="handleSearch">搜索</button>
      </div>

      <h2 class="section-title">仅浏览过的{{ historyLimit }}件商品</h2>

      <div v-if="loading" class="history-feedback">正在加载浏览记录...</div>
      <div v-else-if="error" class="history-feedback error">{{ error }}</div>
      <div v-else-if="displayedRecords.length === 0" class="history-feedback empty">
        暂无浏览记录
      </div>
      <div v-else class="product-list">
        <div
          v-for="record in displayedRecords"
          :key="record.productId + (record.viewedAt || '')"
          class="product-carding"
        >
          <div class="product-imageing">
            <img :src="record.imageUrl || defaultImage" :alt="record.productName || record.productId" />
          </div>
          <div class="product-nameing">{{ record.productName || '未知商品' }}</div>
          <div class="product-reviewing">
            <div class="user">浏览时间：{{ formatDateTime(record.viewedAt) }}</div>
            <div v-if="record.category">分类：{{ record.category }}</div>
            <div>价格：{{ formatPrice(record.price) }}</div>
            <div v-if="record.platformName">平台：{{ record.platformName }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCurrentUser, getBrowseHistory } from '@/api'
import { useUserStore } from '@/stores/user'

const HISTORY_LIMIT = 30

const router = useRouter()
const userStore = useUserStore()

const isSubmenuOpen = ref(false)
const loading = ref(false)
const error = ref('')
const historyRecords = ref([])
const searchQuery = ref('')

const defaultImage = new URL('@/assets/Logo.png', import.meta.url).href
const defaultAvatar = defaultImage

const avatarUrl = computed(() => userStore.info?.icon || defaultAvatar)
const displayName = computed(() => userStore.userName || '用户')
const historyLimit = computed(() => HISTORY_LIMIT)

const toggleSubmenu = () => {
  isSubmenuOpen.value = !isSubmenuOpen.value
}

const isSuccess = (res) => res && (res.code === 0 || res.code === 200)

const ensureUserInfo = async () => {
  if (!userStore.isLoggedIn) {
    router.push('/user-login')
    return false
  }
  if (!userStore.info) {
    try {
      const res = await getCurrentUser()
      if (isSuccess(res) && res.data) {
        userStore.setUserInfo(res.data)
      }
    } catch (err) {
      console.warn('获取用户信息失败，即将返回登录页', err)
      userStore.clearAuth()
      router.push('/user-login')
      return false
    }
  }
  return true
}

const loadBrowseHistory = async () => {
  loading.value = true
  error.value = ''
  try {
    const res = await getBrowseHistory({ limit: HISTORY_LIMIT })
    if (isSuccess(res)) {
      const payload = res.data || {}
      historyRecords.value = Array.isArray(payload.records) ? payload.records : []
    } else {
      throw new Error(res?.message || '加载浏览记录失败')
    }
  } catch (err) {
    console.error('加载浏览记录失败:', err)
    error.value = err.message || '加载浏览记录失败，请稍后重试'
    historyRecords.value = []
  } finally {
    loading.value = false
  }
}

const formatPrice = (value) => {
  if (value === null || value === undefined || value === '') {
    return '¥0.00'
  }
  const num = Number(value)
  if (Number.isFinite(num)) {
    return `¥${num.toFixed(2)}`
  }
  return `¥${value}`
}

const formatDateTime = (value) => {
  if (!value) return '未知时间'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return value
  }
  return date.toLocaleString('zh-CN', { hour12: false })
}

const displayedRecords = computed(() => {
  if (!searchQuery.value.trim()) {
    return historyRecords.value
  }
  const keyword = searchQuery.value.trim().toLowerCase()
  return historyRecords.value.filter((record) => {
    const name = record.productName?.toLowerCase() || ''
    const category = record.category?.toLowerCase() || ''
    const productId = record.productId?.toLowerCase() || ''
    return (
      name.includes(keyword) ||
      category.includes(keyword) ||
      productId.includes(keyword)
    )
  })
})

const handleSearch = () => {
  searchQuery.value = searchQuery.value.trim()
}

onMounted(async () => {
  const ok = await ensureUserInfo()
  if (ok) {
    await loadBrowseHistory()
  }
})
</script>

<style scoped>
@import '@/CSS/UserPublicCss.css';

/* 右侧内容区域：唯一可滚动的部分 */
@import '@/CSS/ViewRecording.css';

.history-feedback {
  margin: 20px;
  padding: 20px;
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  color: #333;
  text-align: center;
}

.history-feedback.error {
  border-color: #ff6b6b;
  color: #d84315;
}

.history-feedback.empty {
  color: #666;
}
</style>
